package com.maxd.modules.selfshop.merchants.service;

import com.maxd.error.ExceptionEnum;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.AdminInfo;
import com.maxd.model.Msg;
import com.maxd.modules.selfshop.merchants.entity.SelfMerchantApply;
import com.maxd.modules.selfshop.merchants.entity.SelfStore;
import com.maxd.modules.selfshop.merchants.respository.SelfMerchantApplyJpaRepository;
import com.maxd.modules.selfshop.merchants.respository.SelfStoreJpaRepository;
import com.maxd.modules.selfshop.util.SmsUtil;
import com.maxd.respository.admin.AdminJpaRepository;
import com.maxd.respository.admin.AdminRepository;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.msg.MsgJpaRepository;
import com.maxd.service.sysRole.SysUserRoleService;
import com.maxd.service.userinfo.IUserService;
import com.maxd.utils.DateUtil;
import com.maxd.utils.MD5Util;
import com.maxd.utils.UpdateJPAUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class SelfMerchantApplyServiceImpl implements SelfMerchantApplyService{
    @Autowired
    private SelfMerchantApplyJpaRepository jpaRepository;
    @Autowired
    private AdminJpaRepository adminService;
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SelfStoreJpaRepository selfStoreJpaRepository;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private IUserService userService;
    @Autowired
    private MsgJpaRepository msgJpaRepository;

    /**
     * 商家入驻列表
     * @param page 页数
     * @param size 条数
     * @param storeName 商家名称
     * @param legalPhone 注册手机号
     * @param storeType 店铺类型
     * @param status 状态
     * @param createTimeStart 申请时间开始区间
     * @param createTimeEnd 申请时间结束区间
     * @return
     */
    @Override
    public Result findAll(Integer page, Integer size, String storeName, String legalPhone, Integer storeType, Integer status, String createTimeStart, String createTimeEnd) {
        //按照时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createTime")));
        //构造自定义查询条件
        Specification<SelfMerchantApply> queryCondition = new Specification<SelfMerchantApply>() {
            @Override
            public Predicate toPredicate(Root<SelfMerchantApply> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(storeName)) {
                    predicateList.add(criteriaBuilder.like(root.get("storeName"), "%"+storeName+"%"));
                }
                if (StringUtils.isNotEmpty(legalPhone)) {
                    predicateList.add(criteriaBuilder.equal(root.get("legalPhone"), legalPhone));
                }
                if (storeType != 0) {
                    predicateList.add(criteriaBuilder.equal(root.get("storeType"), storeType));
                }
                if (status != 0) {
                    predicateList.add(criteriaBuilder.equal(root.get("status"), status));
                }
                if (StringUtils.isNotEmpty(createTimeStart)) {
                    predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), createTimeStart));
                }
                if (StringUtils.isNotEmpty(createTimeEnd)) {
                    predicateList.add(criteriaBuilder.lessThan(root.get("createTime"), createTimeEnd));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    /**
     * 商户入驻申请
     * @param entity
     * @return
     */
    @Override
    public Result saveBody(SelfMerchantApply entity) {
        //判断商户名称、手机号
        SelfMerchantApply s = jpaRepository.checkStoreName(entity.getStoreName());
        if (s != null){
            return ResultUtil.error(-1,"商户名称重复");
        }
        SelfMerchantApply phone = jpaRepository.checkLegalPhone(entity.getLegalPhone());
        if (phone!= null){
            return ResultUtil.error(-1,"负责人的手机号已经注册过了！");
        }
        AdminInfo login = adminRepository.login(entity.getLegalPhone());
        if(login!=null){
            return ResultUtil.error(-1,"负责人的手机号已经注册过了！");
        }
        entity.setCreateTime(DateUtil.createTime());
        entity.setStatus(1); //审核状态（1待处理 2通过 3拒绝）
        entity.setMoney(new BigDecimal("0.00")); //金额为0
        SelfMerchantApply save = jpaRepository.save(entity);
        //发送短信
        SmsUtil.send(entity.getLegalPhone(), "", "1");
        return ResultUtil.success(save);
    }

    @Override
    public Result updateBody(SelfMerchantApply entity) {
        entity.setStatus(1); //待处理
        entity.setCreateTime(DateUtil.createTime());
        UpdateJPAUtil.copyNullProperties(jpaRepository.findById(entity.getId()).orElse(null), entity);
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result findOne(Long id) {
        return ResultUtil.success(jpaRepository.findById(id).orElse(null));
    }

    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id);
        return ResultUtil.success();
    }

    /**
     * 处理审核
     * @param id
     * @param status 审核状态（1待处理 2通过 3拒绝）
     * @param refundReason 拒绝原因
     * @return
     */
    @Override
    public Result deal(Long id, Integer status,BigDecimal rate, String refundReason) {
        //1.保存审核信息
        SelfMerchantApply one = jpaRepository.findById(id).orElse(null);
        one.setStatus(status);
        one.setRefundReason(refundReason);
        SelfMerchantApply update = jpaRepository.save(one);
        if (status == 2){//审核成功
            //创建店铺
            SelfStore store = new SelfStore();
            store.setMerchantId(update.getId()); //商户id
            store.setCreateTime(DateUtil.createTime()); //创建时间
            store.setStoreName(one.getStoreName()); //店铺名称
            store.setSale(0); //销量为0
            store.setBanStatus(1); //店铺状态
            store.setMarginStatus(1); //保证金状态；未缴纳
            store.setScore(100); //店铺分数
            store.setRate(rate);
            store.setCategoryId(one.getCategoryId());
            store.setCategoryName(one.getCategoryName());
            String address;
            //1个人 存store 2个体工商 存company 3 4 也是
            if(one.getStoreType()==1){
                address = one.getStoreAddressProvince()+one.getStoreAddressCity()+one.getStoreAddressDistrict()+one.getStoreAddressDetail();
            }else{
                address = one.getCompanyAddressProvince()+one.getCompanyAddressCity()+one.getCompanyAddressDistrict()+one.getCompanyAddressDetail();
            }
            store.setShipAddress(address); //地址
            store.setRefundAddress(address); //退货地址
            store.setRefundContact(one.getLegal()); //退货人
            store.setRefundMobile(one.getLegalPhone()); //退货电话
            SelfStore selfStore = selfStoreJpaRepository.save(store);
            //注册账号
            AdminInfo a = new AdminInfo();
            a.setCreateAt(DateUtil.createTime());
            a.setPhone(one.getLegalPhone());
            a.setUserName("多商户："+one.getStoreName());
            a.setPwd(MD5Util.encoderByMd5(one.getLegalPhone()));
            a.setMerchantId(update.getId()); //商户id
            a.setStoreId(selfStore.getStoreId()); //店铺id
            a.setAdminType(2);
            AdminInfo admin = adminService.save(a);
            //保存角色权限多商户角色
            List<Long> role = new ArrayList<>();
            role.add(1L); //多商户管理员角色id为1
            sysUserRoleService.saveOrUpdate(admin.getId(),role);
            //发送短信
            SmsUtil.send(one.getLegalPhone(), "", "2");
        }else if(status == 3){
            //拒绝
            //发送短信
            SmsUtil.send(one.getLegalPhone(), "", "3");
        }
        return ResultUtil.success(update);
    }


    @Override
    public Result reviewCode(String phone) {
        SelfMerchantApply s = jpaRepository.checkLegalPhone(phone);
        if (s == null){
            return ResultUtil.error(-1,"查询不到商户信息");
        }
        //审核状态（1待处理 2通过 3拒绝）
        if(s.getStatus() == 1){
            return ResultUtil.error(-1,"正在审核中");
        }else if (s.getStatus() == 2){
            return ResultUtil.error(-1,"已经审核通过");
        }else{
            //发送验证码:将验证码传入
            int code = (int) ((Math.random() * 9 + 1) * 100000);
            SmsUtil.send(phone, String.valueOf(code), "4");
            System.out.println("sendMsg code is " + code);
            Msg byPhone = msgJpaRepository.findByPhone(phone);
            if (byPhone != null) {
                byPhone.setCode(String.valueOf(code));
                byPhone.setPhone(phone);
                msgJpaRepository.save(byPhone);
            } else {
                Msg msg = new Msg();
                msg.setCode(String.valueOf(code));
                msg.setPhone(phone);
                msgJpaRepository.save(msg);
            }
            return ResultUtil.success();
        }
    }

    @Override
    public Result review(String phone, String msg) {
        Msg byPhoneAndCode = msgJpaRepository.findByPhoneAndCode(phone, msg);
        if (byPhoneAndCode == null) {
            return ResultUtil.error(ExceptionEnum.CODE_ERROR);
        }
        SelfMerchantApply s = jpaRepository.checkLegalPhone(phone);
        if (s == null){
            return ResultUtil.error(-1,"查询不到商户信息");
        }
        //审核状态（1待处理 2通过 3拒绝）
        if(s.getStatus() == 1){
            return ResultUtil.error(-1,"正在审核中");
        }else if (s.getStatus() == 2){
            return ResultUtil.error(-1,"已经审核通过");
        }else{
            return ResultUtil.success(s);
        }
    }

    @Override
    public Result updateZhiFuBao(Long merchantId, String zhiFuBaoAccount, String zhiFuBaoName) {
        SelfMerchantApply s = jpaRepository.findById(merchantId).orElse(null);
        s.setZhiFuBaoAccount(zhiFuBaoAccount);
        s.setZhiFuBaoName(zhiFuBaoName);
        SelfMerchantApply update = jpaRepository.save(s);
        return ResultUtil.success(update);
    }

    @Override
    public Result updateWx(Long merchantId, String wxImg){
        SelfMerchantApply s = jpaRepository.findById(merchantId).orElse(null);
        s.setWxImg(wxImg);
        SelfMerchantApply update = jpaRepository.save(s);
        return ResultUtil.success(update);
    }

}
